package com.dream.libmp3lame.sample;

import android.content.Context;

import com.dream.libmp3lame.MP3Lame;
import com.dream.libmp3lame.utils.ArrayUtils;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;

public class MP3DecoderSample {
    private final MP3Lame mLame = new MP3Lame();
    private FileOutputStream mOutput = null;
    private final String mp3Path;
    public MP3DecoderSample(Context ct,
                            String mp3Path,
                            int sample,
                            int channel,
                            int bitRate,
                            int quality,
                            boolean isVbr){

        this.mp3Path = mp3Path;

        mLame.initEnc(sample,sample,channel,channel,
                bitRate,quality,
                isVbr);

        try {
            mOutput = new FileOutputStream(mp3Path);
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        }
    }

    public void write(byte[] pcm,int size){
        if (size <= 0){
            return;
        }

        short[] shorts = new short[pcm.length/2];
        ArrayUtils.toShortLittle(pcm,shorts,size,true);

        byte[] mp3 = new byte[shorts.length * 5 / 4 + 7200];
        int mp3Len = mLame.encode(shorts,size/2,mp3);
        try {
            if (mp3Len > 0){
                mOutput.write(mp3,0,mp3Len);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void release(){
        byte[] data = new byte[7200];
        int len = mLame.flush(data);

        if (len > 0){
            try {
                mOutput.write(data,0,len);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        mLame.release();
    }


}
